

package com.soso.base.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.soso.base.util.log.Logger;
import com.soso.base.util.other.ETagComputeUtils;

/**
 * 
 * @author speed
 *
 */
public class ETagContentFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, 
    		FilterChain chain) throws IOException, ServletException {
    	HttpServletRequest servletRequest = (HttpServletRequest) request;
     	HttpServletResponse servletResponse = (HttpServletResponse) response;

      	ByteArrayOutputStream baos = new ByteArrayOutputStream();
     	ETagResponseWrapper wrappedResponse = new ETagResponseWrapper(servletResponse, baos);
     	chain.doFilter(servletRequest, wrappedResponse);

      	byte[] bytes = baos.toByteArray();

      	String token = '"' + ETagComputeUtils.getMd5Digest(bytes) + '"';
     	servletResponse.setHeader("ETag", token); // always store the ETag in the header

      	String previousToken = servletRequest.getHeader("If-None-Match");
     	if (previousToken != null && previousToken.equals(token)) { // compare previous token with current one
     		Logger.info("ETag match: returning 304 Not Modified");
     		servletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED);
     		// use the same date we sent when we created the ETag the first time through
     		servletResponse.setHeader("Last-Modified", servletRequest.getHeader("If-Modified-Since"));
     	} else  { 		// first time through - set last modified time to now 
     		Calendar cal = Calendar.getInstance();
     		cal.set(Calendar.MILLISECOND, 0);
     		Date lastModified = cal.getTime();
     		servletResponse.setDateHeader("Last-Modified", lastModified.getTime());

     		Logger.info("Writing body content");
     		servletResponse.setContentLength(bytes.length);
     		ServletOutputStream sos = servletResponse.getOutputStream();
     		sos.write(bytes);
     		sos.flush();
     		sos.close();
     	}
    }
    
	public void init(FilterConfig filterConfig) throws ServletException {

	}
	
	public void destroy() {
	}

}
